package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GZIPCompressesGivenFileIntoNewFile {
	public static final int BUFF_SIZE = 2048;

	public static void compressFile(final File toCompress,
	                                final File destinationFile) throws IOException {
		streamToCompressedFile(new FileInputStream(toCompress),
				destinationFile);
	}


	public static void streamToCompressedFile(final InputStream istream,
	                                          final File destinationFile) throws IOException {
		OutputStream gzStream = null;
		InputStream biStream = null;
		try {
			gzStream = new GZIPOutputStream(new BufferedOutputStream(
					new FileOutputStream(destinationFile)), BUFF_SIZE);
			biStream = new BufferedInputStream(istream, BUFF_SIZE);
			transferStream(biStream, gzStream);
		} finally {
			if (gzStream != null) {
				gzStream.close();
			}
			if (biStream != null) {
				biStream.close();
			}
		}
	}


	protected static void transferStream(final InputStream istream,
	                                     final OutputStream ostream) throws IOException {
		final byte[] inBuf = new byte[BUFF_SIZE];
		int readBytes = istream.read(inBuf);
		while (readBytes >= 0) {
			ostream.write(inBuf, 0, readBytes);
			readBytes = istream.read(inBuf);
		}
	}
}
